package structure.ProxyPattern.practice;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyDesign {
    public static void main(String[] args) {
//        RealImage realImage = new RealImage("xxxx文件,png");
        Image proxyBuyHouse = (Image) Proxy.newProxyInstance(
                Image.class.getClassLoader(),
                new Class[]{Image.class},
                new DynamicProxyHandler("xxxx文件,png")
                );
        proxyBuyHouse.display();
        proxyBuyHouse.display();
        proxyBuyHouse.display();
        proxyBuyHouse.display();

    }
}

/**
 * 目标接口
 * */
interface Image{
    void display();
}

/**
 * 目标实现类
 * */
class RealImage implements Image{

    private String fileName;

    public RealImage(String fileName){
        this.fileName = fileName;
        load(fileName);
    }

    public void load(String fileName){
        System.out.println("磁盘 Loading" + fileName);
    }

    @Override
    public void display() {
        System.out.println("display");
    }
}

/**
 * 代理类
 * */
class ProxyImage implements Image{

    private RealImage realImage; //代理对象
    private String fileName;

    public ProxyImage(String fileName){
        this.fileName = fileName;
    }

    @Override
    public void display() {
        if (this.realImage == null){ //模拟减少磁盘加载功能
            realImage = new RealImage(fileName);
        }
        realImage.display();
    }
}

/**
 * jdk 动态代理处理器
 * */
class DynamicProxyHandler implements InvocationHandler {

    private Object realImage;
    private String fileName;

    public DynamicProxyHandler(String fileName){
        this.fileName = fileName;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //代理前逻辑
        if (realImage == null){
            this.realImage = new RealImage(fileName);
        }
        Object result = method.invoke(realImage, args);
        //代理后逻辑
        return result;
    }
}